import {reqOrderSubmit} from '../../api/good'
import { reqCartList, reqCartRemove } from "../../api/cart";
import {removeStorage,setStorage} from "../../utils/storage"
Page({
  data: {
    allchecked: false,
    cartList:[],
    totalprice:0
  },

  onChange(event) {
    // console.log(event)
    
    //更改对应的check属性值
    const index = event.currentTarget.dataset.index
    const result = event.detail
    let list = this.data.cartList
    list[index].checked = result
    
    
    this.setData({
      cartList:list
    });

    this.calulatePrice()
  },

  checkall(event){
    // console.log(event)

    let list = this.data.cartList

    //保持全选或者全不选
    for(let i = 0;i<list.length;i++ ){
      list[i].checked = event.detail
    }

    this.setData({
      allchecked:event.detail,
      cartList:list
    })

    this.calulatePrice()
  },

  onShow(){
    this.getCartList()
    this.setData({
      totalprice:0
    })  },

  async getCartList(){
    const {data} = await reqCartList()
    // console.log(data)

    //为购物车每一个对象增加一个checked属性值

    for (let i = 0; i < data.length; i++) {
      data[i].checked = false;
      data[i].index = i;
    }

    this.setData({
      cartList:data
    })
  },

  calulatePrice(){
    const list = this.data.cartList
    let totalprice = 0
    for(let i =0;i<list.length;i++){
      if(list[i].checked == true){
      totalprice += list[i].priceTotal
      }
    }

    this.setData({
      totalprice:totalprice
    })

    // console.log(totalprice)
  },

  async checkout(){
    const list = this.data.cartList
    
    let param = list.filter(item => item.checked).map(
      item =>{
        return {
          productId:item.productId,
          amount:item.amount,
          businessType:3
          //TODO 也许对于加入购物车的商品需要溯源 这里为方便先统一为c端客户下单
      }
      })

    let ids = list.filter(item => item.checked).map(
        item =>{
          return {
            id:item.id,
        }
    })

    // console.log(param)
    

    const {data} = await reqOrderSubmit(param)
    
    this.removeCart(ids)
    
    // console.log(data)
    removeStorage('ordersubmitgoods')
    setStorage('ordersubmitgoods',data)
    wx.navigateTo({
      url: '/pages/ordersubmit/ordersubmit',
    })
  },

  async removeCart(ids){
    const idArray  = ids.map(item=> item.id.toString())
    console.log(idArray)
    await reqCartRemove(idArray)
  }

})